package com.clw.commander;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chengliwei on 2018/12/11.
 */
public class CommanderParser {

    private Map<String, CmdOption> options;
    private String[] params;

    public CommanderParser() {
        this.options = new HashMap<>();
        addOption("-h", "--help", false, "print help info");
    }

    public void addOption(CmdOption option) {
        options.put(option.getShortName(), option);
        // 暂时只支持了short name
    }

    public void addOption(String shortName, String verboseName, boolean needValue, String help) {
        CmdOption option = new CmdOption();
        option.setShortName(shortName);
        option.setVerboseName(verboseName);
        option.setNeedValue(needValue);
        option.setHelp(help);
        addOption(option);
    }

    public void parse(String[] args) {
        for (int i = 0; i < args.length; ) {
            String arg = args[i];
            if (isVerboseName(arg)) {
                // TODO: 2018/12/12 verbose parse
            } else if (isShortName(arg)) {
                CmdOption option = options.get(arg);
                if (option.isNeedValue()) {
                    option.setValue(args[i + 1]);
                    option.setParsed(true);
                    i++;
                }
            } else {
                int size = args.length - i;
                params = new String[size];
                System.arraycopy(args, i, params, 0, size);
                break;
            }
            i++;
        }
    }

    private boolean isVerboseName(String arg) {
        return arg.startsWith("--") && arg.length() > 2;
    }

    private boolean isShortName(String arg) {
        return arg.startsWith("-") && arg.length() > 1;
    }

    public void printHelpInfo() {
        System.out.println("Usage:");
        for (CmdOption option : options.values()) {
            System.out.println(option.helpString());
        }
    }

    public boolean hasOption(String key) {
        return options.get(key) != null ? options.get(key).isParsed() : false;
    }

    public String getOptionValue(String key) {
        return options.get(key) != null ? options.get(key).getValue() : null;
    }

    public String getClassPath() {
        return params[0];
    }
}
